package com.nononsenseapps.feeder.model.category

import com.gitee.wsl.jvm.store.mmkv.MMKVStoreServer
import com.gitee.wsl.struct.category.TreeNodeItemWarp
import com.gitee.wsl.struct.tree.TreeHelper
import com.gitee.wsl.struct.tree.TreeNodeManager
import com.gitee.wsl.struct.tree.bean.TreeItem
import com.gitee.wsl.struct.tree.bean.TreeNodeItem
import com.nononsenseapps.feeder.db.view.PreviewItem

object FeedItemCategoryHelper {
    val saveTagMap by lazy {
        TreeHelper.TreeNodeItemMap(MMKVStoreServer.get(), "feed_item_category_tree_map")
    }

    val saveTagList :List<String>
        get() {
            return saveTagMap.getValueList().map { it.name }
        }

    val saveTagValueMap:Map<String,String>
        get(){
            return saveTagMap.saveMap.mapValues { it.value.name }
        }

    fun addCustomTagTree(name:String):TreeItem?{
        if(saveTagList.contains(name))
            return null
        val treeItem=TreeItem(name)
        saveTagMap.put(treeItem.id,treeItem)
        return treeItem
    }

    fun removeCustomTagTree(id:String){
        if(!saveTagMap.containsKey(id))
            return
        saveTagMap.delete(id)
    }

    fun saveTree(treeId: String){
        saveTagMap.saveTree(treeId)
    }


    fun buildTreeCategoryRoot(treeId:String): TreeNodeItemWarp {

        val saveTagTree=saveTagMap.get(treeId)

        val root=TreeNodeItemWarp(saveTagTree!!.root)

        initTreeWarpRoot(root,saveTagTree.root)

        return root
    }



    private fun initTreeWarpRoot(root:TreeNodeItemWarp, saveTagTreeRoot: TreeNodeItem){
        saveTagTreeRoot.childNodes.forEach {
            val itemNode=TreeNodeItemWarp(it)
            root.addSubCategoryItem(itemNode )
            if(!it.isLeaf())
                initTreeWarpRoot(itemNode,it)
        }
    }


    fun initTreeFeedItemList(root:TreeNodeItemWarp, feedItemList:List<PreviewItem>){
        val nodeCategoryMap = mutableMapOf<Any,Any>()

        TreeNodeManager.treeToMap(root,nodeCategoryMap)

        feedItemList.forEach feedItemFo@{ feedItem ->
            feedItem.tags().forEach {tag->
                if(tag.isNotEmpty()) {
                    nodeCategoryMap[tag]?.let {
                        it as TreeNodeItemWarp
                        it.addSubCategoryItem(FeedItemTreeWarp(feedItem))
                        return@feedItemFo
                    }
                }
            }
            root.addSubCategoryItem(FeedItemTreeWarp(feedItem))
        }
    }

    fun getTreeItem(treeName: String): TreeItem? {
      return saveTagMap.get(treeName)
    }

}
